install.packages("fUnitRoots")
install.packages("forecast")
library(plyr)
library(ggplot2)
library(tseries)
library(fUnitRoots)
library(forecast)
urdfTest(ts[[1]]$x)
datax<-product_1$pr$s$h_h_h
ts<-lgts(product_1$pr$s$h_h_h,n=3,start=15,end=29,k=4)
sd(ts[[1]]$trend,na.rm=TRUE)
sd(ts[[1]]$x,na.rm=TRUE)
sd(ts[[1]]$random[1:(60*6)],na.rm=TRUE)
sd(ts[[1]]$random[(60*6):(110*6)],na.rm=TRUE)
arima1<-auto.arima(ts[[1]]$x,D=0,start.P = 2,start.Q = 1,max.p=12,max.q=2,start.p=12,start.q=0,trace=T,ic="bic")

tsp<-lgts(product_1$pr$s$h_h_h,n=3,start=15,end=30,k=4)
lg<-plts(ts=ts,lag.max=150,lgval=0.15,dif=24,sen=TRUE)
lg[[2]]
lg[[1]]

ARIMA<-arima(ts[[1]]$x,order = c(6,0,0),seasonal=list(order=c(2,1,1),period=24),method = "CSS")
forecast<-forecast.Arima(ARIMA,h=24,level=c(99.5))
plot.forecast(forecast,)
ARIMA$aic
#summary(ARIMA)
pre=predict(ARIMA,n.ahead=4*6) 
U=pre$pred + 1.96*pre$se 
L=pre$pred - 1.96*pre$se
ts.plot(tsp[[1]]$x,pre$pred,col=1:2)  
lines(U,col="blue",lty="dashed") 
lines(L,col="blue",lty="dashed") 
which.max(apply(product_1$pr$s$h_h_h,1,sum))
names(tsp[[1]]$x)
data<-tsp[[1]]$x
data<-as.data.frame(cbind(((15*24):(30*24))/24,data))
colnames(data)<-c("时间","销售量")
LU<-as.data.frame(cbind(((29*24+1):(30*24))/24,L,U,pre$pred))
colnames(LU)<-c("时间","L","U","pred")
data
myaim<-function(data,id=1,start=15,end=29,k=4){
  ts<-lgts(data,n=id,start,end,k)
  tsp<-lgts(data,n=id,start,end+1,k)
  TT<-k*(7-length(ts[[2]]))
  ARIMA<-arima(ts[[1]]$x,order = c(TT/4,0,0),seasonal=list(order=c(2,1,1),period=TT),method = "CSS")
  pre=predict(ARIMA,n.ahead=TT) 
  U=pre$pred + 1.96*pre$se 
  L=pre$pred - 1.96*pre$se
  data<-tsp[[1]]$x
  data<-as.data.frame(cbind(((start*TT):((end+1)*TT))/TT,data))
  colnames(data)<-c("时间","销售量")
  LU<-as.data.frame(cbind(((end*TT+1):((end+1)*TT))/TT,L,U,pre$pred))
  colnames(LU)<-c("时间","L","U","pred")
  ggplot(data=data,aes(x=时间,y=销售量))+
    geom_line()+geom_line(data=LU,aes(x=时间,y=pred),colour="red")+
    geom_polygon(aes(x=c(时间,时间[TT:1]),y=c(L,U[TT:1])),data=LU,alpha=0.3)+
    xlim(c(25,30))+
    labs(title = paste("店铺",rownames(data)[id]))+
    theme(plot.title = element_text(size = rel(2)))+
    geom_vline(xintercept =end, colour="green", linetype = "longdash",size=1)
}
myaim(63)
rownames(datax)[1]
ggplot()+geom_smooth(data=LU,aes(ymin = L, ymax = U), stat="identity")














